package logic

import (
	"context"
	"fmt"
	"models"

	"shop_srv/internal/svc"
	"shop_srv/shop_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type CarPushLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCarPushLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CarPushLogic {
	return &CarPushLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CarPushLogic) CarPush(in *shop_srv.CarPushRequest) (*shop_srv.CarPushResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("card_%d:%d", in.UserId, in.GoodsId)
	var good models.Goods
	if err := models.DB.Where("id = ?", in.GoodsId).Limit(1).Find(&good).Error; err != nil {
		return nil, err
	}
	if good.ID == 0 {
		return nil, fmt.Errorf("商品不可用")
	}
	if good.GoodsStock < in.Number {
		return nil, fmt.Errorf("库存不足")
	}
	models.Rdb.HSet(models.Ctx, key, "id", good.ID, "name", good.GoodsName, "number", in.Number)
	return &shop_srv.CarPushResponse{}, nil
}
